<template>
  <el-dialog 
    title="新增填单任务" 
    :visible.sync="showDialog" 
    width="50%"
    @close="$emit('close')"
  >
    <el-form :model="form" :rules="rules" ref="form" label-width="120px">
      <el-form-item label="任务名称" prop="task_name">
        <el-input v-model="form.task_name"></el-input>
      </el-form-item>
      <el-form-item label="填单人" prop="login_user">
        <el-input v-model="form.login_user"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="login_pwd">
        <el-input v-model="form.login_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="Excel文件" prop="excel">
        <el-upload
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          :action="''"
          accept=".xlsx,.xls"
        >
          <el-button size="small" type="primary">选择文件</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传Excel文件，且必须包含必填字段
          </div>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </span>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'

export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: [],
      form: {
        task_name: '',
        login_user: '',
        login_pwd: ''
      },
      rules: {
        task_name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        login_user: [{ required: true, message: '请输入填单人', trigger: 'blur' }],
        login_pwd: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  methods: {
    handleFileChange(file) {
      this.fileList = [file]
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid && this.fileList.length > 0) {
          const formData = new FormData()
          formData.append('file', this.fileList[0].raw)
          formData.append('task_name', this.form.task_name)
          formData.append('login_user', this.form.login_user)
          formData.append('login_pwd', this.form.login_pwd)
          
          request({
            url: '/smart/fillform/upload',
            method: 'post',
            data: formData
          }).then(response => {
            this.$emit('success')
            this.$message.success('提交成功!')
          }).catch(error => {
            this.$message.error(error.response.data.error)
          })
        } else {
          this.$message.error('请填写完整信息并上传文件')
        }
      })
    }
  }
}
</script>